// http.js//1. 加载 http 核心模块
const WebSocketServer = require('ws').Server
const chokidar = require('chokidar')
const moment = require('moment')
const yaml = require('yamljs')
const fs = require("fs")
const dateTimePattern = 'YYYY年MM月DD日HH时mm分ss秒'
const dateTimePattern2 = 'YYYYMMDDHHmmssSSS'
const file = 'config.yml'
const wss = new WebSocketServer({ port: 3001 })

var config = yaml.parse(fs.readFileSync(file).toString());

function log(content) {
	console.log(moment().format(dateTimePattern) + ': ' + content)
}

var monitorPort = config.monitor.port
var monitorPath = config.monitor.path
var reloadBaseUrl = config.monitor['reload-base-url']
var reloadBasePath = config.monitor['reload-base-path']
var includePatternRegs = (config.monitor['include-pattern']||[]).map(regPattern => new RegExp(regPattern))

log(`监听路径: ${monitorPath}`);

chokidar.watch(monitorPath).on('change', function(path){
	log(`监听到 ${path} 文件变化`)

	if(	
		path.length <= monitorPath.length  
		|| includePatternRegs.length === 0 
		|| includePatternRegs.findIndex(reg => reg.test(path)) < 0
	) {
		log(`忽略 ${path} 文件`)
	}
	
	let subPath = path.substring(monitorPath.length)
	let paths = subPath.split(/[\\\.]/).filter(item => !!item)
	
	if(paths.length <= 0) {
		return
	}
	
	let ext = paths.pop()
	
	if(ext.toLowerCase() !== 'vue') {
		return
	}
	
	let responseData = {
		name: paths[paths.length - 1] + '.vue',
		path: `${reloadBaseUrl}${paths.join('/')}.vue`,
		uniqueId: `${reloadBasePath}_${paths.join('_')}.vue`
	}

	log(JSON.stringify(responseData))
	
	if(!!GWS) {
		GWS.forEach(item => {
			item.socket.send(JSON.stringify(responseData))
		})
	}
})

var GWS = []

wss.on('connection', function (ws) {
	let newId = moment().format(dateTimePattern2)
	
	GWS.push({
		id: newId,
		socket: ws
	})
	
	log('监听到新连接 ' + newId + ', 当前共 ' + GWS.length + ' 个活跃连接')
	
    ws.on('message', function (message) {
        //打印客户端监听的消息
        log(message)
    })
	
	ws.on('close', () => {
		log('连接断开 ' + newId)
		
		let index = GWS.findIndex(item => item.id === newId)
		if(index >= 0) {
			GWS.splice(index, 1)
			log('连接信息删除成功, 当前共 ' + GWS.length + ' 个活跃连接')
		}
	})
})

log(`websocket 服务器启动成功了，可以通过 ws://127.0.0.1:${monitorPort}/ 进行访问`)